--[[
-- @Author:      feilong
-- @DateTime:    2020-11-13 23:05:48
-- @Description: redis消息的处理
-- @Example:
	local data = g.Message():callService(".redis", "redis_cmd", nil, "get", "num")
	g.log:debug("redis data", data)


--]]
local rabbit = require("snex.rabbitmqstomp")

local cjson = require "cjson"
local debug = debug


local M = class("Hander")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function M:ctor()
    local server_config = g.getServerConf()
    local conf = server_config.rabbit
    self.host = conf[1]
    self.account = conf[2]
    self.db_info = conf

    self.conn = nil
    g.fork(function()
        while not self.conn do
            g.sleep(100)
        end
        self.conn:receive()
    end)
    self:register()
end

--注册本服务里的消息
function M:register()
    g.register("sub", handler(self, self.onSub))
    g.defCallback(self,self.defaultCommand)
end

--从连接池里取一个服务
function M:getConnect()    
    if self.conn then
        return self.conn
    end
    local ok, ret = xpcall(rabbit.connect, debug.traceback, self.host, self.account)
    while not ok do
        g.log:error('failed to connect rabbit',ret, self.host, self.account)
        g.sleep(500)   --one second
        ok,ret = xpcall(rabbit.connect, debug.traceback, self.host, self.account)
    end
    self.conn = ret
    return ret
end


---------------------------------------------------------
-- CMD
---------------------------------------------------------

function M:onSub(headers, ...)
    g.log:debug("onSub headers:", headers, ...)
    local conn = self:getConnect()
    --订阅
    conn:subscribe(
        headers,
        function(data)
            --收到消息
            g.log:debug("subscribe consumed:", data)
            g.log:debug("111subscribe consumed:", cjson.decode(data))
            --mq:unsubscribe(headers)
        end
    )
    return true
end

function M:defaultCommand(...)
    return self:onSub(...)
end





return M